package controller;

import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import dao.ChangeDao;
import dao.impl.ChangeDaoImpl;
import entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(urlPatterns = "/changeController")
public class ChangeController extends HttpServlet {

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doPost(req,resp);
    }
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        String op=req.getParameter("op");
        HttpSession session=req.getSession(true);
        PrintWriter out=resp.getWriter();
        if ("xugai".equals(op)){
            String newPassword = req.getParameter("newPassword");
//            String password=req.getParameter("password");
            String user_id=req.getParameter("user_id");
            ChangeDao dao=new ChangeDaoImpl();
            int a=0;
            try {
                a=dao.show(newPassword, Integer.parseInt(user_id));
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            if (a>0){
               out.write("修改成功");
            }
        }
        if ("quxian".equals(op)){
            String role=req.getParameter("role");
            ChangeDao dao=new ChangeDaoImpl();
            List<User>list1=null;
            try {
                list1=dao.show1(role);
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            if (list1 !=null){
                session.setAttribute("roleOptions",list1);
                req.getRequestDispatcher("Change/user_permission.jsp").forward(req,resp);
            }
        }
        if ("getAllUsers".equals(op) || "chaxu".equals(op)) {
            String username = "chaxu".equals(op) ? req.getParameter("seach") : null;
            String role = "chaxu".equals(op) ? req.getParameter("newRole1") : null;
            String pageStr = req.getParameter("page");
            String pageSizeStr = req.getParameter("pageSize");
            int page;
            try {
                page = (StringUtils.isNullOrEmpty(pageStr)) ? 1 : Integer.parseInt(pageStr);
            } catch (NumberFormatException e) {
                // 当pageStr不是有效整数时，使用默认值1
                page = 1;
                // 可选：记录日志或返回错误信息
                // log.warn("Invalid page parameter: " + pageStr + ", using default value 1");
            }
            int pageSize = StringUtils.isNullOrEmpty(pageSizeStr) ? 5 : Integer.parseInt(pageSizeStr);
            
            ChangeDao dao = new ChangeDaoImpl();
            try {
                // 获取总记录数
                int totalCount = dao.getTotalCount(username, role);
                // 计算总页数(向上取整)
                int totalPages = (int) Math.ceil((double)totalCount / pageSize);
                // 确保页码在有效范围内
                page = Math.max(1, Math.min(page, totalPages == 0 ? 1 : totalPages));
                
                // 获取分页数据
                List<User> list = dao.getUsersByPage(username, role, page, pageSize);
                
                // 构造返回结果
                Map<String, Object> result = new HashMap<>();
                result.put("list", list);
                result.put("page", page);
                result.put("totalPages", totalPages);
                result.put("totalCount", totalCount);
                
                resp.setContentType("application/json;charset=UTF-8");
                resp.getWriter().write(JSON.toJSONString(result));
            } catch (Exception e) {
                e.printStackTrace();
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "数据库操作失败");
            }
        }
        if ("character".equals(op)){
            String role=req.getParameter("newRole");
            String user_id=req.getParameter("userId");
            ChangeDao dao=new ChangeDaoImpl();
            int s=0;
            try {
                s=dao.show3(role, Integer.parseInt(user_id));
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            if (s>0){
                out.write("修改成功");
            }else{
                out.write("修改失败");
            }

        }
    }
}
